import { useEffect, useMemo, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useLocation, useNavigate } from 'react-router-dom';
import { Tabs, Button, Input, Tag, Skeleton, App } from 'antd';
import loadable from '@loadable/component';
import pMinDelay from 'p-min-delay';
import useAuthAction from '@/hooks/useAuthAction';

import Empty from '@/components/Empty';
import { getUserInfo, getContribList, getHaveMerchList, getWantMerchList, getFollowUserList, followUser, unFollowUser,
  checkFollowed, getFollowStats, updateAvatar, updateUsername, updatePhone,
 } from '@/service/api';
 import { logout } from '@/service/base';
import { setStore } from '@/reducers/common';
import { ACCOUNT, UPLOAD_FILE_OSS } from '@/config/url';
import useDevice, { DEVICES } from '@/hooks/useDevice';
import styles from './index.module.scss';

const List = loadable(() => pMinDelay(import('@/pages/Fragment/List'), 0), { fallback: <Skeleton style={{padding:12}} active/> });
const EditPhoneModal = loadable(() => pMinDelay(import('./EditPhoneModal'), 0));
const EditUsernameModal = loadable(() => pMinDelay(import('./EditUsernameModal'), 0));
const UploadFiles = loadable(() => pMinDelay(import('@/components/UploadFiles'), 0));

export default () => {
  const initState = () => ({
    tab: 'contrib',
    accountUser: {},
    followUsers: [],
    hasFollowed: false,
    items: [],
    loading: false,
    pageNo: 1,
    pageSize: 10,
    total: 0,
    showEditPhoneModal: false,
    showEditUsernameModal: false,

    followCount: 0,
  });
  const [state, setState] = useState(initState);
  const { message } = App.useApp();
  const { userInfo = {} } = useSelector(s => s.common || {});
  const dispatch = useDispatch();
  const location = useLocation();
  const hasLogin = !!userInfo?.id;
  const navigate = useNavigate();
  const withAuth = useAuthAction();
  const isDesktop = useDevice() === DEVICES.DESKTOP;
  const isMobile = useDevice() === DEVICES.MOBILE;
  
  // 使用useLocation来获取URL参数，这样URL变化时会触发重新渲染
  const currentUid = useMemo(() => {
    const searchParams = new URLSearchParams(location.search);
    const uid = searchParams.get('uid');
    // 如果URL参数没有uid，则使用userInfo.id作为默认值
    return uid || userInfo?.id?.toString();
  }, [location.search, userInfo?.id]);
  const isOwn = useMemo(() => {
    const uid = userInfo?.id;
    return !!uid && !!currentUid && uid.toString() === currentUid.toString();
  }, [userInfo, currentUid]);

  const check = async () => {
    if(currentUid && userInfo?.id && userInfo?.id?.toString() !== currentUid.toString()) { // 如果不是自己且是登录状态，那么就检查我是否已关注该用户
      const [res, err] = await checkFollowed({ followeeMemberId: currentUid });
      if (err) return;
      setState(s => ({ ...s, hasFollowed: res?.data || false }));
    }
  };
  const getCoount = async () => {
    const [res, err] = await getFollowStats({ memberId: currentUid });
    if (err) return;
    setState(s => ({ ...s, followCount: res?.data?.followerCount || 0 }));
  };
  // 根据id获取用户信息，校验是否已关注该用户
  const getUserInfoById = async () => {
    if(!currentUid) return;
    const [res, err] = await getUserInfo({memberId: isOwn?'':currentUid}); // 如果是本人就不需要memberId参数，否则就需要 

    check(); // 不用await
    getCoount();

    const accountUser = res?.data?.memberInfo || {}
    setState(o => ({
      ...o,
      accountUser,
    }));
  }
  // 获取关注用户列表，只有自己时才会有请求，他人查看时是没有该模块的
  const getFollowUserListById = async () => {
    if(!currentUid || userInfo?.id?.toString() !== currentUid.toString()) return; // 需要登录状态，且是自己查看自己
    const [res, err] = await getFollowUserList({pageNo: 1, pageSize: 9999});
    if (err) return;
    setState(s => ({ ...s, followUsers: res?.data?.records || [] }));
  };
  // 展示登录弹框
  const showLogin = () => dispatch(setStore({ loginVisible: true }));

  // 跳转用户中心
  const toAccount = id => {
    navigate(`${ACCOUNT}?uid=${id}`);
  };

  // 显示编辑手机号弹框
  const showEditPhoneModal = () => {
    setState(o => ({ ...o, showEditPhoneModal: true }));
  };

  // 关闭编辑手机号弹框
  const hideEditPhoneModal = () => {
    setState(o => ({ ...o, showEditPhoneModal: false }));
  };

  // 确认修改手机号
  const handlePhoneUpdate = (newPhone) => {
    setState(o => ({ 
      ...o, 
      showEditPhoneModal: false 
    }));
    
    // 同时更新store中的userInfo
    dispatch(setStore({ 
      userInfo: { 
        ...userInfo, 
        phone: newPhone 
      } 
    }));
  };

  // 更新头像
  const toUpdateAvatar = async (url) => {
    if(url) {
      const [res, err] = await updateAvatar({avatar: url});
      if (err) {
        message.error(err.message || '头像上传失败');
        return;
      }
      if(OK_CODE === res?.code) {
        message.success(`头像已更新`);

        // 更新store中的userInfo
        dispatch(setStore({ 
          userInfo: { 
            ...userInfo, 
            avatar: url 
          } 
        }));
      }else{
        message.warning(res?.message || '头像更新失败');
      }
    }else{
      message.error(`头像上传失败`);
    }
};
  // 显示编辑用户名弹框
  const showEditUsernameModal = () => {
    setState(o => ({ ...o, showEditUsernameModal: true }));
  };
  // 关闭编辑用户名弹框
  const hideEditUsernameModal = () => {
    setState(o => ({ ...o, showEditUsernameModal: false }));
  };
  // 确认修改用户名
  const handleUsernameUpdate = (newUsername) => {
    setState(o => ({ 
      ...o, 
      showEditUsernameModal: false 
    }));
    
    // 同时更新store中的userInfo
    dispatch(setStore({ 
      userInfo: { 
        ...userInfo, 
        nickName: newUsername 
      } 
    }));
  };

  // 获取列表
  const getList = async (options={}) => {
    const { pageNo, pageSize } = state;
    const { tab, ...rest } = options;
    const realTab = tab || state.tab;
    const queryData = {pageNo, pageSize, ...rest};

    setState(s => ({ ...s, loading: true }));
    try {
      const api = realTab === 'contrib' ? getContribList : realTab === 'mymerch' ? getWantMerchList : getHaveMerchList;
      const [res, err] = await api({...queryData, memberId: currentUid});
      if (err) return;
      const { records, current, total, size } = res?.data || {};
      const items = (1 === current ? [] : state.items).concat(records);

      setState(s => ({
        ...s,
        items,
        pageNo: current,
        pageSize: size,
        total,
        tab: realTab,
      }));
    } finally {
      setState(s => ({ ...s, loading: false }));
    }
  };

  // 加载更多
  const handlePageChange = (pageNo, pageSize) => {
    getList({ pageNo, pageSize });
  };

  // 切换tab时，重置分页和数据
  const changeTab = key => {
    setState(o => ({ ...o, tab: key }));
    getList({ pageNo: 1, tab: key });
  };

  // 关注/取消关注核心逻辑
  const toFollowCore = async () => {
    const{ hasFollowed, followCount } = state;
    const api = hasFollowed ? unFollowUser : followUser;
    if(currentUid && userInfo?.id && userInfo?.id?.toString() === currentUid.toString()) return; // 不能关注自己
    const [res, err] = await api({ followeeMemberId: currentUid });
    if (err) return;
    message.success(hasFollowed ? '取消关注成功' : '关注成功');
    
    // 更新关注状态和关注数量
    const newFollowCount = hasFollowed ? followCount - 1 : followCount + 1;
    setState(s => ({ 
      ...s, 
      hasFollowed: !hasFollowed,
      followCount: Math.max(0, newFollowCount) // 确保关注数量不会小于0
    }));
  };
  // 关注/取消关注（带登录校验）
  const toFollow = withAuth(toFollowCore);

  // 退出登录
  const toLogout = async () => {
    try {
      // 清除 localStorage
      await logout();
      localStorage.removeItem('accessToken');
      dispatch(setStore({userInfo: {}}));
      // 重置页面状态数据
      setState(initState());
      navigate(ACCOUNT);
    } catch (error) {
      console.error('退出登录失败:', error);
    }
  };

  useEffect(() => {
    if (currentUid) {
      // 获取新用户数据
      getUserInfoById();
      getFollowUserListById();
    }
  }, [userInfo, currentUid]);

  // Tabs数据
  const tabItems = useMemo(() => {
    return [
      ...(isOwn && hasLogin ? [{ key: 'contrib', label: '我贡献的' }] : []),
      { key: 'have', label: `${isOwn ? '我' : '他'}有` },
      { key: 'mymerch', label: `${isOwn ? '我' : '他'}要` },
    ];
  }, [hasLogin, isOwn, currentUid]);

  // 初始化数据
  useEffect(() => {
    setState(o => ({...o, tab: isOwn && hasLogin ? 'contrib' : 'have'}));
    getList({ tab: isOwn && hasLogin ? 'contrib' : 'have', pageNo: 1 });
  }, [isOwn, hasLogin]);

  return (
    <div className={styles['account-wrap']}>
      <section className={styles['section']}>
        <div className={styles['section-title']}>
          基础信息
          {
            !isDesktop && hasLogin ?
              <Button size="small" type="primary" shape="round" onClick={toLogout}>退出登录</Button>
              :
              null
          }
        </div>
        <div className={styles['base-info']}>
          <div className={styles['info-row']}>
            { !hasLogin ? <div className={styles['mask']} onClick={showLogin}></div> : null }
            <div className={styles['info-icon']}>
              <UploadFiles
                limit={1}
                action={UPLOAD_FILE_OSS}
                accept="image/*"
                shape="circle"
                value={state.accountUser?.avatar || '/images/default-avatar.png'}
                onChange={toUpdateAvatar}
                isAvatar={true}
                disabled={!hasLogin || !isOwn}
              />
            </div>
            <div className={styles['info-col']}>
              <div className={styles['user-bar']}>
                {
                  currentUid ?
                    <div className={styles['info-item']}>
                      用户名：<span>{state.accountUser?.nickName || '--'}</span>
                      {hasLogin && isOwn ? <Button size="small" type="link" onClick={showEditUsernameModal} style={{ marginLeft: 8 }}>修改</Button> : null}
                    </div>
                    :
                    <span role="button" style={{ cursor: 'pointer' }} onClick={showLogin}>点击登录</span>
                }
              </div>
              
              {
                // 只有登录且是本人时才显示手机/邮箱/微信信息
                hasLogin && isOwn ?
                  (
                    state.accountUser?.email ? 
                      <div className={styles['info-item']}>
                        <div>邮箱：</div><span>{state.accountUser?.email || '--'}</span>
                      </div>
                      :
                      <>
                        <div className={styles['info-item']}>
                          <div>手机号：</div><span>{state.accountUser?.phone || '未绑定'}</span>
                          <Button size="small" type="link" onClick={showEditPhoneModal} style={{ marginLeft: 8 }}>
                            {state.accountUser?.phone ? '修改' : '绑定'}
                          </Button>
                        </div>
                        <div className={styles['info-item']}>
                          <div>微信：</div><span>{state.accountUser?.openid ? '已绑定' : '未绑定'}</span>
                        </div>
                      </>
                  )
                  :
                  null
              }
            </div>
            {
              false && <div className={styles['follow-col']}>
                <div className={styles['follow-count']}>
                  <div>{state.followCount || 0}</div>
                  <div>关注</div>
                </div>
                {
                  // 查看他人页面时显示关注按钮（包括未登录状态）
                  !isOwn && currentUid ?
                    <Button size="small" className={styles['follow-btn']} shape="round" type="primary" onClick={toFollow}>{state.hasFollowed ? '取消' : ''}关注</Button>
                    :
                    null
                }
              </div>
            }
          </div>
        </div>
      </section>

      <section className={styles['section']}>
        <div className={styles['section-title']}>晒谷场</div>
        <div className={styles['tabs']}>
          <Tabs
            activeKey={state.tab}
            onChange={changeTab}
            items={tabItems.map(t => ({
              key: t.key,
              label: t.label,
              children: 
                <List 
                  type={t.key === 'contrib' ? 'mycontrib' : 'mymerch'}
                  dataSource={state.items}
                  loading={state.loading}
                  pagination={{
                    total: state.total,
                    current: state.pageNo,
                    pageSize: state.pageSize,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    hideOnSinglePage: true,
                    size: isMobile ? 'small' : 'default',
                    onChange: handlePageChange,
                  }}
                />
            }))}
          />
        </div>
      </section>

      {
        false && isOwn ?
          <section className={styles['section']}>
            <div className={styles['section-title']}>我关注的</div>
            {
              (state.followUsers || []).length ?
                <div className={styles['follow-list']}>
                  {state.followUsers.map(f => (
                    <Tag key={f.followeeMemberId} className={styles['follow-tag']} onClick={toAccount.bind(null, f.followeeMemberId)}>
                      <span className={styles['follow-avatar']}><img src={f.followeeMemberAvatar ? `${f.followeeMemberAvatar}?x-oss-process=image/resize,p_20` : '/images/default-avatar.png'} alt={f.name || f.nickName} /></span>
                      <span>{f.followeeMemberName}</span>
                    </Tag>
                  ))}
                </div>
                :
                <Empty description="暂无关注" />
            }
          </section>
          :
          null
      }

      <EditPhoneModal
        visible={state.showEditPhoneModal}
        onCancel={hideEditPhoneModal}
        onOk={handlePhoneUpdate}
      />

      <EditUsernameModal
        visible={state.showEditUsernameModal}
        onCancel={hideEditUsernameModal}
        onOk={handleUsernameUpdate}
        currentUsername={state.accountUser?.nickName}
      />
    </div>
  );
};
